package cn.persoo.html_parse.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.google.gson.Gson;

import cn.persoo.html_parse.domain.AnnualReport;
import net.sf.json.JSONArray;

public class Entrance {

	public static void main(String[] args) throws Exception {
		// String webUrl = "http://www.tianyancha.com/company/46817615";
		// HtmlPage page = getHtmlPage(webUrl);
		// Document document = Jsoup.parse(page.asXml(), webUrl);
		// System.err.println("查询数据成功");
		Entrance entrance = new Entrance();
		String companyId = "46817615";
		entrance.mainPersonParse(companyId);
		entrance.shareholderParse(companyId);
		entrance.investmentParse(companyId);
		entrance.changeRecordParse(companyId);
		entrance.annualReportParse(companyId);
	}

	private HtmlPage getHtmlPage(String url) throws Exception {
		final WebClient webClient = new WebClient(BrowserVersion.CHROME);
		// 1 启动JS
		webClient.getOptions().setJavaScriptEnabled(true);
		// 2 禁用Css，可避免自动二次请求CSS进行渲染
		webClient.getOptions().setCssEnabled(false);
		// 3 启动客户端重定向
		webClient.getOptions().setRedirectEnabled(true);
		// 4 js运行错误时，是否抛出异常
		webClient.getOptions().setThrowExceptionOnScriptError(false);
		// 5 设置超时
		webClient.getOptions().setTimeout(30000);

		final HtmlPage page = webClient.getPage(url);
		System.err.println("查询中，请稍候");
		// 等待JS驱动dom完成获得还原后的网页
		webClient.waitForBackgroundJavaScript(3000);
		webClient.close();
		return page;
	}

	/**
	 * 主要人员
	 * @param document
	 */
	public void mainPersonParse(String companyId) {
		String url = "http://www.tianyancha.com/expanse/staff.json?id=" + companyId + "&ps=20&pn=1";
		try {
			Response res = Jsoup.connect(url).header("Accept", "*/*").header("Accept-Encoding", "gzip, deflate")
					.header("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3")
					.header("Content-Type", "application/json;charset=UTF-8")
					.header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:48.0) Gecko/20100101 Firefox/48.0")
					.timeout(10000).ignoreContentType(true).execute();
			res.body();
			System.err.println("主要人员：" + res.body());
			String data = new JSONObject(res.body()).get("data").toString();
			String result = new JSONObject(data).get("result").toString();
			JSONArray arry = JSONArray.fromObject(result);
			List<Object> list = new ArrayList<>();
			for (Object object : arry) {
				Map<String, String> hashMap = new HashMap<>();
				String name = new JSONObject(object.toString()).get("name").toString();
				String title = JSONArray.fromObject(new JSONObject(object.toString()).get("typeJoin").toString()).get(0)
						.toString();
				hashMap.put("name", name);
				hashMap.put("title", title);
				list.add(hashMap);
			}
			System.out.println(new Gson().toJson(list));
		} catch (IOException e) {
			e.printStackTrace();
		} // .get();
	}

	/**
	 * 股东信息
	 * @param document
	 */
	@SuppressWarnings("unchecked")
	public void shareholderParse(String companyId) {
		String url = "http://www.tianyancha.com/expanse/holder.json?id=" + companyId + "&ps=20&pn=1";
		try {
			Response res = Jsoup.connect(url).header("Accept", "*/*").header("Accept-Encoding", "gzip, deflate")
					.header("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3")
					.header("Content-Type", "application/json;charset=UTF-8")
					.header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:48.0) Gecko/20100101 Firefox/48.0")
					.timeout(10000).ignoreContentType(true).execute();
			res.body();
			System.err.println("股东信息：" + res.body());

			String data = new JSONObject(res.body()).get("data").toString();
			String result = new JSONObject(data).get("result").toString();
			JSONArray arry = JSONArray.fromObject(result);
			List<Object> list = new ArrayList<>();
			for (Object object : arry) {
				Map<String, String> hashMap = new HashMap<>();
				HashMap<String, String> capitalMap = new HashMap<>();
				String name = new JSONObject(object.toString()).get("name").toString();
				List<Object> list2 = new ArrayList<>();
				JSONArray capitalArray = JSONArray
						.fromObject(new JSONObject(object.toString()).get("capital").toString());
				for (int i = 0, length = capitalArray.size(); i < length; i++) {
					capitalMap.put("planAmount",
							new JSONObject(capitalArray.get(i).toString()).get("amomon").toString());
					capitalMap.put("planTime", new JSONObject(capitalArray.get(i).toString()).get("time").toString());
					capitalMap.put("planType", new JSONObject(capitalArray.get(i).toString()).get("paymet").toString());
					list2.add(capitalMap);
				}
				JSONArray capitalActlArray = JSONArray
						.fromObject(new JSONObject(object.toString()).get("capitalActl").toString());
				for (int i = 0, length = capitalActlArray.size(); i < length; i++) {
					capitalMap = (HashMap<String, String>) list2.get(i);
					capitalMap.put("realAmount",
							new JSONObject(capitalActlArray.get(i).toString()).get("amomon").toString());
					capitalMap.put("realTime",
							new JSONObject(capitalActlArray.get(i).toString()).get("time").toString());
					capitalMap.put("realType",
							new JSONObject(capitalActlArray.get(i).toString()).get("paymet").toString());
				}
				hashMap.put("capital", new Gson().toJson(list2));
				hashMap.put("name", name);
				list.add(hashMap);
			}
			System.out.println(new Gson().toJson(list));
		} catch (IOException e) {
			e.printStackTrace();
		} // .get();
	}

	/**
	 * 对外投资
	 * @param document
	 */
	public void investmentParse(String companyId) {
		String url = "http://www.tianyancha.com/expanse/inverst.json?id=" + companyId + "&ps=20&pn=1";
		try {
			Response res = Jsoup.connect(url).header("Accept", "*/*").header("Accept-Encoding", "gzip, deflate")
					.header("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3")
					.header("Content-Type", "application/json;charset=UTF-8")
					.header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:48.0) Gecko/20100101 Firefox/48.0")
					.timeout(10000).ignoreContentType(true).execute();
			res.body();
			System.err.println("对外投资：" + res.body());

			String data = new JSONObject(res.body()).get("data").toString();
			String result = new JSONObject(data).get("result").toString();
			System.out.println(result);
		} catch (IOException e) {
			e.printStackTrace();
		} // .get();
	}

	/**
	 * 变更记录
	 * @param document
	 */
	public void changeRecordParse(String companyId) {
		String url = "http://www.tianyancha.com/expanse/changeinfo.json?id=" + companyId + "&ps=100&pn=1";
		try {
			Response res = Jsoup.connect(url).header("Accept", "*/*").header("Accept-Encoding", "gzip, deflate")
					.header("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3")
					.header("Content-Type", "application/json;charset=UTF-8")
					.header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:48.0) Gecko/20100101 Firefox/48.0")
					.timeout(10000).ignoreContentType(true).execute();
			res.body();
			System.err.println("变更记录：" + res.body());

			String data = new JSONObject(res.body()).get("data").toString();
			String result = new JSONObject(data).get("result").toString();
			System.out.println(result);
		} catch (IOException e) {
			e.printStackTrace();
		} // .get();

	}

	/**
	 * 企业年报
	 * @param document
	 */
	public void annualReportParse(String companyId) {
		String url = "http://www.tianyancha.com/expanse/annu.json?id=" + companyId + "&ps=1&pn=1";
		try {
			Response res = Jsoup.connect(url).header("Accept", "*/*").header("Accept-Encoding", "gzip, deflate")
					.header("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3")
					.header("Content-Type", "application/json;charset=UTF-8")
					.header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:48.0) Gecko/20100101 Firefox/48.0")
					.timeout(10000).ignoreContentType(true).execute();
			res.body();
			System.err.println("企业年报：" + res.body());

			String data = new JSONObject(res.body()).get("data").toString();
			JSONArray arry = JSONArray.fromObject(data);
			for (Object object : arry) {
				AnnualReport annualReport = new AnnualReport();
				String year = new JSONObject(object.toString()).get("reportYear").toString();
				String reportUrl = "http://www.tianyancha.com/reportContent/" + companyId + "/" + year;
				try {
					HtmlPage htmlPage = getHtmlPage(reportUrl);
					System.err.println(">>>>>>>" + htmlPage.asXml());

					Document document = Jsoup.parse(htmlPage.asXml(), reportUrl);
					annualReport.setCompanyName(document.getElementsByClass("report_all_title").html());

					// 企业基本信息
					Elements baseInfo = document.getElementsByClass("report_baseInfo").select("table").select("tr");
					for (int i = 0, length = baseInfo.size(); i < length; i++) {
						Elements elementsTds = baseInfo.get(i).select("td");
						switch (i) {
						case 0:
							annualReport.setRegNumber(elementsTds.get(1).text());
							annualReport.setCompanyName(elementsTds.get(3).text());
							break;
						case 1:
							annualReport.setPhoneNumber(elementsTds.get(1).text());
							annualReport.setPostCode(elementsTds.get(3).text());
							break;
						case 2:
							annualReport.setManageState(elementsTds.get(1).text());
							annualReport.setEmployeeNum(elementsTds.get(3).text());
							break;
						case 3:
							annualReport.setEmail(elementsTds.get(1).text());
							annualReport.setHasWeb(elementsTds.get(3).text());
							break;
						case 4:
							annualReport.setPostalAddress(elementsTds.get(1).text());
							annualReport.setHasShareHolder(elementsTds.get(3).text());
							break;
						default:
							break;
						}
					}

					// 网站或网店信息
					Elements website = document.getElementsByClass("report_website").select("table").select("tbody").select("tr");
					Map<Object, Object> webInfo = new HashMap<>();
					for (int i = 0, length = website.size(); i < length; i++) {
						Elements elementsTds = website.get(i).select("td").select("div");
						webInfo.put("type", elementsTds.get(0));
						webInfo.put("name", elementsTds.get(1));
						webInfo.put("url", elementsTds.get(2));
					}
					annualReport.setWebInfo(webInfo);
					System.err.println(new Gson().toJson(annualReport));
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} // .get();

	}

	/**
	 * 分支机构
	 * @param document
	 */
	public void branchParse(Document document) {

	}

}